package ru.fadeev.crammer.ui;

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.*;


/**
 * ArrowOptionPane extends JOptionPane, so user can switch between buttons with
 * arrow keys.
 * @author Konstantin Fadeyev
 *
 */
public class ArrowOptionPane extends JOptionPane {

	public static int showConfirmDialog(Component parentComponent, Object message, String title, int optionType) {
		final JOptionPane pane = new JOptionPane();
		pane.setOptionType(optionType);
		pane.setMessage(message);
		pane.setMessageType(JOptionPane.QUESTION_MESSAGE);
		JDialog dialog = pane.createDialog(parentComponent, title);
		final JPanel buttonPanel = (JPanel)(pane.getComponent(1));
		int buttonsCount = buttonPanel.getComponentCount();
		for(int i = 0; i < buttonsCount - 1; i++) {
			final JButton button = (JButton)(buttonPanel.getComponent(i));
			final int buttonIndex = i;
			button.addKeyListener(
					new KeyAdapter() {
						public void keyPressed(KeyEvent ev) {
							if((ev.getKeyCode() == KeyEvent.VK_RIGHT || ev.getKeyCode() == KeyEvent.VK_DOWN) && (ev.getModifiers()==0)) {
								if(button.hasFocus()) {
									JButton nextButton = (JButton)(buttonPanel.getComponent(buttonIndex+1));
									nextButton.requestFocus();
								}								
							}
						}
					});
			
		}
		for(int i = 1; i < buttonsCount; i++) {
			final JButton button = (JButton)(buttonPanel.getComponent(i));
			final int buttonIndex = i;
			button.addKeyListener(
					new KeyAdapter() {
						public void keyPressed(KeyEvent ev) {
							if((ev.getKeyCode() == KeyEvent.VK_LEFT || ev.getKeyCode() == KeyEvent.VK_UP) && (ev.getModifiers()==0)) {
								if(button.hasFocus()) {
									JButton prevButton = (JButton)(buttonPanel.getComponent(buttonIndex-1));
									prevButton.requestFocus();
								}								
							}
						}
					});
			
		}
		dialog.setVisible(true);
		Integer selectedValue = (Integer)(pane.getValue());
		return selectedValue.intValue();
	}
}
